package com.xing.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xing.util.JsonDateValueProcessor;

@Controller
public abstract class BaseAction extends ActionSupport {
	//sm7tY4hs4jt2
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(BaseAction.class);

	@JSON(serialize=false)
	@SuppressWarnings("unchecked")
	protected Map<String, Object> getRequest() {
		return (Map<String, Object>) ActionContext.getContext().get("request");
	}
	
	@JSON(serialize=false)
	protected Map<String, Object> getSession() {
		return (Map<String, Object>) ActionContext.getContext().getSession();
	}
	
	protected void setMessage(String key, String msg) {
		getRequest().put(key, msg);
	}
	
	private String deleteId;
	public void setDeleteId(String deleteId) {
		this.deleteId = deleteId;
	}

	@JSON(serialize=false)
	public String getDeleteId() {
		return deleteId;
	}
	
	private InputStream dataGrid;
	@JSON(serialize=false)
	public InputStream getDataGrid() {
		return dataGrid;
	}
	
	public void setDataGrid(Map<String, Object> map) {
		try {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
			
			JSONObject fromObject = JSONObject.fromObject(map, jsonConfig);
			
			dataGrid =
					new ByteArrayInputStream(fromObject.toString().getBytes("UTF-8"));
					
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public abstract String dataGrid();
	
	// 分页页数
	private int page;
	// 分页条数
	private int rows;

	@JSON(serialize=false)
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	@JSON(serialize=false)
	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
}
